package com.xsh.web.weixin;


import com.xsh.config.WxConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import weixin.popular.api.SnsAPI;
import weixin.popular.bean.sns.SnsToken;
import weixin.popular.bean.user.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author lixing
 * @date 2021/5/25 15:47
 */
@Slf4j
@Controller
@RequestMapping("/auth")
public class WxAuthController {

    @Autowired
    private WxConfig wxConfig;

    /**
     * 微信授权登录，用code换取snstoken，再用snstoken换取userinfo
     * @param param
     * @param request
     * @param response
     * @return
     */
    @RequestMapping
    public String list(@RequestParam Map<String, String> param, HttpServletRequest request, HttpServletResponse response){
        if (null == param || null == param.get("code")){
            //处理非法请求
            return "error";
        }
        String code = param.get("code");
        SnsToken stoken = SnsAPI.oauth2AccessToken(wxConfig.getAppID(), wxConfig.getAppsecret(), code);
        User user = SnsAPI.userinfo(stoken.getAccess_token(), stoken.getOpenid(), "zh_CN");
        //获取token
        //String token = TokenManager.getDefaultToken();
        //微信登录信息
        request.getSession().setAttribute("user",user);
        request.getSession().setAttribute("openId",stoken.getOpenid());
        //数据入库

        //登录前请求地址
        String uri = param.get("uri");
        return "redirect:"+uri;
    }
}
